package com.mf.service.authority.impl;


import com.mf.common.sso.LoginContext;
import com.mf.dao.authority.RoleInfoDao;
import com.mf.dao.authority.UserInfoDao;
import com.mf.dao.authority.UserRoleRelationDao;
import com.mf.domain.authority.RoleInfo;
import com.mf.domain.authority.UserInfo;
import com.mf.domain.authority.UserRoleRelation;
import com.mf.service.authority.UserRoleRelationService;
import com.mf.service.framework.GenericService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户角色关联信息Service层实现类
 * User: zhaoming
 * DateTime: 2016-07-15
 * To change this template use File | Settings | File Templates.
 **/
@Service
public class UserRoleRelationServiceImpl extends GenericService<UserRoleRelation> implements UserRoleRelationService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserRoleRelationDao userRoleRelationDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private RoleInfoDao roleInfoDao;

    /**
     * 查询用户角色映射列表
     * @param userRoleRelation 用户角色关联信息Domain
     * @return 用户角色映射列表
     */
    public List<UserRoleRelation> selectByCondition(UserRoleRelation userRoleRelation){
        List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
        for(UserRoleRelation data : userRoleRelations){

            UserInfo userInfo = new UserInfo();
            userInfo.setUserCode(data.getUserCode());
            List<UserInfo> userInfos = userInfoDao.selectByCondition(userInfo);
            if(CollectionUtils.isNotEmpty(userInfos)){
                data.setUserName(userInfos.get(0).getUserName());
            }

            RoleInfo roleInfo = new RoleInfo();
            roleInfo.setRoleCode(data.getRoleCode());
            List<RoleInfo> roleInfos = roleInfoDao.selectByCondition(roleInfo);
            if(roleInfos!=null && roleInfos.size()>0){
                data.setRoleName(roleInfos.get(0).getRoleName());
            }
        }

        return userRoleRelations;
    }

    /**
     * 检查重复数据
     * @param userRoleRelation 用户角色关联信息Domain
     * @return 验证结果
     */
    public Map<String, Object> checkRepeat(UserRoleRelation userRoleRelation){
        Map<String, Object> map = new HashMap<>();
        List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
        if(CollectionUtils.isNotEmpty(userRoleRelations)){
            map.put("error", "存在重复数据");
        }else{
            map.put("ok", "");
        }
        return map;
    }

    /**
     * 验证用户编码
     * @param userCode 用户编码
     * @param assignRoleCode 角色编码
     * @return 验证结果
     */
    public Map<String, Object> checkUserCode(String userCode, String assignRoleCode) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserCode(userCode);
        List<UserInfo> userInfos = userInfoDao.selectByCondition(userInfo);
        if (userInfos != null && userInfos.size()>0) {
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setUserCode(userCode);
            userRoleRelation.setRoleCode(assignRoleCode);
            List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
            if (CollectionUtils.isNotEmpty(userRoleRelations)) {
                map.put("error", "该用户已存在");
            }else{
                map.put("ok", "");
            }
        } else {
            map.put("error", "不存在的用户编码");
        }
        return map;
    }

    /**
     * 获取角色信息
     * @param userRoleRelation 用户角色关联信息Domain
     * @return
     */
    public List<Map<String, Object>> getRoles(UserRoleRelation userRoleRelation){
        List<Map<String, Object>> result = new ArrayList<>();
        Set<String> set = new HashSet();
        List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
        for(UserRoleRelation data : userRoleRelations){
            set.add(data.getRoleCode());
        }

        List<RoleInfo> roleInfos = roleInfoDao.selectByCondition(new RoleInfo());
        for(RoleInfo data : roleInfos){
            Map<String, Object> map = new HashMap<>();
            map.put("roleCode", data.getRoleCode());
            map.put("roleName", data.getRoleName());
            map.put("flag", false);
            if(set.contains(data.getRoleCode())){
                map.put("flag", true);
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 分配角色
     * @param userCode 流程用户编码
     * @param roleCode 角色编码
     */
    @Transactional
    public boolean assignRole(String userCode, String roleCode){
        boolean flag = true;
        try{
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setUserCode(userCode);
            List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
            if(CollectionUtils.isNotEmpty(userRoleRelations)){
                userRoleRelationDao.deleteByPrimaryKeys(userRoleRelations);
            }

            if(StringUtils.isNotBlank(roleCode)){
                String[] roleCodes = roleCode.split(",");
                for(String data : roleCodes){
                    UserRoleRelation userRole = new UserRoleRelation();
                    userRole.setUserCode(userCode);
                    userRole.setRoleCode(data);
                    userRole.setCreateUser(LoginContext.getLoginUser().getUserCode());
                    userRole.setCreateTime(new Date());
                    userRole.setUpdateUser(LoginContext.getLoginUser().getUserCode());
                    userRole.setUpdateTime(new Date());
                    userRoleRelationDao.insert(userRole);
                }
            }
        }catch(Exception e){
            flag = false;
            logger.error("分配角色失败: "+ e.getMessage(), e);
        }

        return flag;
    }

    /**
     * 获取用户信息
     * @param userRoleRelation 用户角色关联信息Domain
     */
    public List<Map<String, Object>> getUsers(UserRoleRelation userRoleRelation){
        List<Map<String, Object>> result = new ArrayList<>();
        Set<String> set = new HashSet();
        List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
        for(UserRoleRelation data : userRoleRelations){
            set.add(data.getUserCode());
        }

        List<UserInfo> userInfos = userInfoDao.selectByCondition(new UserInfo());
        for(UserInfo data : userInfos){
            Map<String, Object> map = new HashMap<>();
            map.put("userCode", data.getUserCode());
            map.put("userName", data.getUserName());
            map.put("flag", false);
            if(set.contains(data.getUserCode())){
                map.put("flag", true);
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 分配用户
     * @param userCode 用户编码
     * @param roleCode 角色编码
     */
    @Transactional
    public boolean assignUser(String userCode, String roleCode){
        boolean flag = true;
        try{
            UserRoleRelation userRoleRelation = new UserRoleRelation();
            userRoleRelation.setRoleCode(roleCode);
            List<UserRoleRelation> userRoleRelations = userRoleRelationDao.selectByCondition(userRoleRelation);
            if(CollectionUtils.isNotEmpty(userRoleRelations)){
                userRoleRelationDao.deleteByPrimaryKeys(userRoleRelations);
            }

            if(StringUtils.isNotBlank(userCode)){
                String[] userCodes = userCode.split(",");
                for(String data : userCodes){
                    UserRoleRelation userRole = new UserRoleRelation();
                    userRole.setUserCode(data);
                    userRole.setRoleCode(roleCode);
                    userRole.setCreateUser(LoginContext.getLoginUser().getUserCode());
                    userRole.setCreateTime(new Date());
                    userRole.setUpdateUser(LoginContext.getLoginUser().getUserCode());
                    userRole.setUpdateTime(new Date());
                    userRoleRelationDao.insert(userRole);
                }
            }
        }catch(Exception e){
            flag = false;
            logger.error("分配用户失败: "+ e.getMessage(), e);
        }

        return flag;
    }

}
